/**
 * 新开页面的业务js
 */

// 全局变量
var yiyuanId = window.parent.yiyuanId;
var bck01;// 部门ID
var vaa01;// 病人id
var vaa05;// 病人姓名
var vac01;// 就诊ID
var acf01;// 门诊还是住院的标识
//var bce01;// 当前登录医师ID//在jsp页面中从session中获取
var bce03;
var hccode;//医院编码
//var loginName = $.cookie("loginName");//在jsp页面中从session中获取
//--------------------------------------------------------
var addTrIndex=1;// 中药增加行的个数
var checkdeArr=new Array();
var topTab;// 医嘱当前激活的页签
var rightTab;// 右侧常用项目当前激活的页签
var geiyaoHtml;// 给药途径集合
var zhenLiaoPinCiHtml;// 治疗频次集合in
var zhenLiaoPinCiHtml2;// 中药治疗频次集合
var zyzhixingkeshi46;// 中药执行科室
var zhiXingXingZhiHtml;// 执行性质集合
var bck01ListHtml;// 科室集合
var activeAdviceInputId;// 当前激活的医嘱单元格的input框
var zhongyaoyongfaHtml;// 中药用法集合
var zhongyaojiaozhuHtml;// 中药脚注集合
var zhongyaojianfaHtml;// 中药煎法
var zhiliaoAdviceList;// 治疗方案医嘱
var jyyangbenleixing;// 检验样本
var jyyangbenleixingList;//检验样本list
var fujianshoushuListHtml;// 附加手术集合
var jijiaxingzhiListHtml;// 计价集合
var mazuiHtml='';// 手术麻醉集合
var yongyaomudiHtml; // 用药目的（公共）
var shoushurenyuanHtml;//手术人员
var bingrenVaoList;//病人常用诊断
var zhixingkeshi1Html;//执行科室下拉列表
var otherPinciHtml;//其它类型频次
var kaizhuyishiHtml;//开嘱医师下拉列表
var qiekoudengjiHtml;//手术医嘱切口等级
var xiangmuguishuHtml;//项目归属
// 界面初始化完成后加载的脚本
var isSave;//验证标志
var valueArr = {};//参数
var geiyaozhixingListHtml;//给药执行下拉
var findYaofangMap;//药品默认执行科室参照Map
var offset = 0;//搜索医嘱的起始索引
var fanganbdo01; //树节点的id

var jibingList=[];//疾病数据集合

/*
 * 分页参数
 */
var pageSize=10;
var curr=1;
$(document).ready(function() {
	//初始化solr索引
//	initSolr();
	skin();
	//加载默认参数
	getAllParams();
	initGloableParams();// 初始化全局变量
	loadAllSelectVal();// 加载所有下拉列表数据----数据库加载
//	loadAllSelectVal_redis();//加载redis数据
	
	//初始化诊断框
	initDiagnoseByParam($("#diagnose_tip"));
//	//新开诊断编辑执行
//	var dataStr=$("#dataStr").val();
//	var dataObj=dataStr?JSON.parse(dataStr):'';
//	if(dataObj)//编辑
//	 {
//		var cbm01 = dataObj.cbm01;
//		editZhenDuanEvent(cbm01);
//		editAdviceByType(cbm01);
//	 }
//	else
//	 {
//		debugger;
//		if (valueArr["p_100_105002_401"]=="1")
//		{
//			addZhenDuanEvent(0);//新开加载所有诊断
//		}
//		var datastr = $($(window.parent.document).find(".yizhu_details")[0]).attr("data-info");
//		if(datastr){
//			var  obj =  JSON.parse(datastr);
//		}
//	 }
//	xySelectDiv();
	reloadPatientInfo(vac01);//病人信息展示
	//侧栏控制区域hover事件
	var rightTabFlag = true;
    $(".right-container-content").hover(function () {
    	$(".slide-control").find(".slide-control-btn").fadeIn(0);
    }, function () {
    	$(".slide-control").find(".slide-control-btn").fadeOut(0);
    });
    //侧栏区域hover事件
    $(".slide-control").hover(function () {
    	$(".slide-control").find(".slide-control-btn").fadeIn(0);
    }, function () {
    	$(".slide-control").find(".slide-control-btn").fadeOut(0);
    });
    //控制按钮点击事件
    $(".slide-control").click(function () {
        if (rightTabFlag) {
        	$('#controlRightTabDiv').animate({'width':"99%"},"fast");
        	$(".right-container").addClass('hidden');
        	rightTabFlag = false;
        } else {
        	$('#controlRightTabDiv').animate({'width':"80%"},"fast");
        	$(".right-container").removeClass('hidden');
        	rightTabFlag = true;
        }
    });
    coverEvent();//遮盖层点击事件，隐藏医嘱列表，及清空input
    //ichek初始化
    iChenckInit($("#send_is_print"));
    $("select").select2();
});


//初始化solr索引库数据
function initSolr()
{
//	$.get(rootUrl+"/doctoradvice/initLucenceIndex",{},function(){});
}
//表格时间填充
function setTime(lastTimeInput){
	var date=new Date();
	$(lastTimeInput).val(date.Format("yyyy-MM-dd hh:mm:ss"));
}
//遮盖层点击事件
function  coverEvent(){
	$("#cover").on("click",function(){
	  $(".changeTdDiv").hide();
  	  $("#cover").addClass("hidden");
//  	  $("#" + activeAdviceInputId).val("");
	})
}

//获取界面参数设置
function getAllParams()
{
	debugger;
	valueArr = parent.valueArr;
//	$.ajax({
//		url : rootUrl + "/patientsearch/findSysparams",
//		data : {userid:userId,bck01:bck01},
//		async : false,
//		success : function(data) {
//			var list = data.list;
//			for(var i = 0;i<list.length;i++)
//			{  
//				valueArr[list[i]["para_key"]] = list[i]["value"];
//			}
//		}
//	});
	var url = rootUrl + "/patientsearch/findYaofang1";
	debugger;
	$.ajax({url:url,data:{bau01:'53',corporationid:yiyuanId},async:false,type:'get',dataType:'json',success:function(data){
		findYaofangMap = data.map;
	}});
}

//加载医嘱的表格
function init()
{
	var preType = setPreCategory();
	// 检验
	$('#new_order_list a[href="#Jianyan"]').tab('show');
	JianyanTable();
	// 加载西药第一行
	$('#new_order_list a[href="#Xiyao"]').tab('show');
	westMedicineTable();
	// 中药
	$('#new_order_list a[href="#Zhongyao"]').tab('show');
	chinaMedicineTable();
	// 检查
	$('#new_order_list a[href="#Jiancha"]').tab('show');
	JianchaTable();
	// 手术
	$('#new_order_list a[href="#Shoushu"]').tab('show');
	shoushuTable();
	//治疗
	$('#new_order_list a[href="#Zhiliao"]').tab('show');
	zhiliaoTable();

//	//卫生材料
 	$('#new_order_list a[href="#Cailiao"]').tab('show');
	cailiaoTable();

	
	//icheck初始化
	iChenckInit($(".main_continer").find('input'));
	isChoseAll("xk_jy_table");
	isChoseAll("xk_jc_table");
	isChoseAll("west_medicine_table");
	isChoseAll("china_medicine_table");
	isChoseAll("xk_shoushu_table");
	isChoseAll("xk_zhiliao_table");
	var dataC = new Date().Format("hh:mm");
	if(valueArr['p_9999_9999_99']=="1"&& (dataC>=valueArr['p_9999_9999_100'] || dataC<=valueArr['p_9999_9999_101']))
	{
		console.log("now is "+dataC);
		$($(".tscf")[0]).val("2").trigger("change");
		$($(".tscf")[1]).val("2").trigger("change");
		$($(".tscf")[2]).val("2").trigger("change");
		$($(".tscf")[3]).val("2").trigger("change");
		$($(".tscf")[4]).val("2").trigger("change");
		$($(".tscf")[5]).val("2").trigger("change");
	}
	else if(valueArr['p_100_105002_414']=="1"&& (dataC>=valueArr['p_100_105002_412'] && dataC<=valueArr['p_100_105002_413']))
	{
		console.log("now is "+dataC);
		$($(".tscf")[0]).val("2").trigger("change");
		$($(".tscf")[1]).val("2").trigger("change");
		$($(".tscf")[2]).val("2").trigger("change");
		$($(".tscf")[3]).val("2").trigger("change");
		$($(".tscf")[4]).val("2").trigger("change");
		$($(".tscf")[5]).val("2").trigger("change");
	}
	else if($("#patienInfoData").val()=="1")
	{
		$($(".tscf")[0]).val("2").trigger("change");
		$($(".tscf")[1]).val("2").trigger("change");
		$($(".tscf")[2]).val("2").trigger("change");
		$($(".tscf")[3]).val("2").trigger("change");
		$($(".tscf")[4]).val("2").trigger("change");
		$($(".tscf")[5]).val("2").trigger("change");
	}
	else
	{
		console.log("now is "+dataC);
	}
	var showT = $("#new_order_list").find(".messageSign:visible").parents("li").find("a").attr("href");
	debugger;
	if (!showT) {
		switch (valueArr['p_100_105002_386']) {
		case '0':
			topTab = "Emr";
			//电子病历聚焦，键盘事件才能起能做用
			window.focus();

			break;
		case '1':
			topTab = "Xiyao";
			break;
		case '3':
			topTab = "Zhongyao";
			break;
		case 'E':
			topTab = "Jiancha";
			break;
		case 'L':
			topTab = "Jianyan";
			break;
		case 'S':
			topTab = "Shoushu";
			break;
		case 'T':
			topTab = "Zhiliao";
			break;
		}
		$('#new_order_list a[href="#' + topTab + '"]').tab('show');
		$('#new_order_list a[href="#' + topTab + '"]').trigger("click");
	}
	else
	{//判断是否编辑的数据
		$('#new_order_list a[href="' + showT + '"]').tab('show');
		$('#new_order_list a[href="' + showT + '"]').trigger("click");
	}
	rightTab = "changyongxiangmu";// 页面初始化后的默认常用项目
	if(topTab !="0")
	{
		changyongxiangmu("changyongxiangmu");//右侧页签常用项目初始化
	}
	if(preType !=1){
		$(".tscf ").val(preType).trigger("change")
	}
}

//加载电子病历
function loadEmrInit(){
	vaa01 =$("#vaa01").val();
	var table = $(window.parent.document).find("#myjiezhenTableList");
	var selectedId = $(table).jqGrid("getGridParam", "selrow");
	var row = $(table).jqGrid("getRowData", selectedId);
	var vac06_1 = row.vac06;
	var vac06;
	if(vac06_1 =="No"){
		vac06=0;
	}else{
		vac06=1;
	}
//	var dzbl = "http://192.168.1.160:8080/emrweb";
//	http://localhost:8080/emrweb/out_interface_doctor.jsp?jsessionids=872634cf-b7db-4435-ad91-f9bdfa6bc0e2&patientId=854493433170108416&patientName=%E5%BC%A0%E4%B8%89&vaa07=854493433170108417&deptId=26&firstOrRepeat=0
	 var src = dzbl + "/out_interface_doctor.jsp?jsessionids=" + 
		$.cookie("jsessionids") + "&patientId=" + vaa01 + "&patientName=" + vaa05 + "&vaa07=" + vac01 + "&deptId=" + bck01+"&firstOrRepeat="+vac06;
    $("#shuxiebingli").attr("src", src);
}

/**
 * 新增同类医嘱单
 */
function newTab()
{
	//add <li>
	var li = $("<li><a href='#Xiyao' data-toggle='tab' onclick='typeClick(\"Xiyao\")'>西成药处方</a></li>");
	$("#new_order_list").append(li);
	//add <div>
	
	//初始化第一行
	if(topTab=="Xiyao")
	{
		westMedicineTable();
		
	}
	else if(topTab=="Zhongyao")
	{
		chinaMedicineTable();
	}
	else if(topTab=="Jianyan")
	{
		JianyanTable();
	}
	else if(topTab=="Jiancha")
	{
		JianchaTable();
	}
	else if(topTab=="Shoushu")
	{
		shoushuTable();
	}
	else if(topTab=="Zhiliao")
	{
		zhiliaoTable();
	}
}


function adviceInputFocus()
{
	  var param=activeTabParam();
	  var cxLastInput= $("#"+param.tableId).find("textarea");// 定义增加行的相对位置
	  $(cxLastInput).last().focus();
	
	
//	if(topTab=="Xiyao")
//	  {
//		  var lastInput = $("#west_medicine_table").find(".xiyao_yznr");
//		  $(lastInput).last().focus();
//		  activeAdviceInputId = lastInput.attr("id");
//	  }
//	  else if(topTab=="Zhongyao")
//	  {
//		  var chLastInput = $("#china_medicine_table").find(".zhongyao_yznr");// 定义增加行的相对位置
//		  $(chLastInput).last().focus();
//	  }
//	  else if(topTab=="Jiancha")
//	  {
//		  var cxLastInput= $("#xk_jc_table").find(".jiancha_yznr");// 定义增加行的相对位置
//		  $(cxLastInput).last().focus();
//	  }else if(topTab=="Jianyan")
//	  {
//		  var cyLastInput= $("#xk_jy_table").find(".jianyan_yznr");// 定义增加行的相对位置
//		  $(cyLastInput).last().focus();
//	  }else if(topTab=="Shoushu")
//	  {
//		  var ssLastInput= $("#xk_shoushu_table").find(".shoushu_yznr");// 定义增加行的相对位置
//		  $(ssLastInput).last().focus();
//	  }else if(topTab=="Zhiliao")
//	  {
//		  var zlLastInput= $("#xk_zhiliao_table").find(".zhiliao_yznr");// 定义增加行的相对位置
//		  $(zlLastInput).last().focus();
//	  }
}



// 初始化全局参数
function initGloableParams() {
	vaa01 = $("#vaa01").val();
	vaa05 = $("#vaa05").val();
	vac01 = $("#vac01").val();
	bck01 = $("#bck01").val();
	acf01 = 1;// 门诊系统默认为1
//	bce01 = $.cookie("employeeId");// 此处从权限系统获取
//	bce01 = bce01;// 此处从权限系统获取
	$.ajax({url:rootUrl+"/clidoctor/getBce03",type:"get",dataType:"json",data:{"bce01":bce01},async:false,success:function(data){bce03 = data.map.bce03}});
	$.ajax({url:rootUrl+"/clidoctor/getHccode",type:"get",dataType:"json",data:{"yiyuanId":yiyuanId},async:false,success:function(data){hccode = data.map.hccode}});

}



// 加载常用项目
function changyongxiangmu(id) {
	$("#changyongContent").empty();
	rightTab = id;
	var that = this;
	$.ajax({
		url : rootUrl + "/doctoradviceeditor/personalOftenList" + topTab,
		type : "post",
		data : {
			"lBCE01" : bce01,
			"lBCK01" : bck01,
			"aACF01" : acf01,
			"bdp02" : '自费'
		},
		dataType : 'json',
		success : function(data) {
			that.laytplUrl(myurl+"/module/changyongxiangmu.html",data,function(data,html){
				$("#changyongContent").empty().append(html);
				addCyxmEvent();
			});
		}
	});
}
function addCyxmEvent(){
	$("#changyongxiangmu_table tr").dblclick(function(){
//		tdCover($(this));
		var dataStr=$(this).attr("data-info");
		var id=$(this).attr("id");
		var dataObj=JSON.parse(dataStr);
		obj=$.extend(dataObj,{'id':id});
		queryAdviceInfo(obj);
	})
}

// 常用治疗方案
function zhiliaofangan(id)
{
	rightTab = id;
		var that = this;
		debugger;
		$.ajax({
			url: rootUrl+"/doctoradviceeditor/personaltherapeuticregimen",
			type: "post",
			data:{"lACF01":acf01,"lBCE01":bce01,"lBCK01":bck01,"currPage":1,"pageSize":30},
			dataType:'json',
			success:function(data)
			{
				that.laytplUrl(myurl+"/module/changyongzhiliao.html",data,function(data,html){
					$("#changyongContent").html(html);
					$(".changeTdDivT").slideDown();
					zhiliaoKeyUp(); //回车搜索
					//加载全部治疗方案
					debugger;
//					$.ajax({
//						url: rootUrl+"/doctoradviceeditor/treelist1",
//						type: "get",
//						data:{"lBEH01":'9',"BCE01":bce01,"BCK01":parent.bck01s,acf01:"(1,3)",fanganshunxu:'123'},
//						dataType:'json',
//						success:function(data)
//						{
//							var list = data.list;
//							$('#treeT').treeview({data: list});
////							$("#tree-tableT").empty();
//							$('#treeT').on('nodeSelected', function(event, data) {
//								// 查询其它项目信息
//								debugger;
//								fanganbdo01 = data["bdo01"];
//								otherListT(data["bdo01"]);
//								});
//							zhiliaoKeyUp(); //回车搜索
//						}
//					});
				});
			}
		});
}

// 常用诊断方案
function zhenduan(id)
{
	rightTab = id;
	var that = this;
		$.ajax({
			url: rootUrl+"/treatment/persontreamentlist",
			type: "get",
			data:{"bce01":bce01,"currPage":1,"pageSize":20},
			dataType:'json',
			success:function(data)
			{
				
				var list=[];
				 for(var i = 0, l = data.list.length; i<l; i++){
					 var x=0;
		                for(var j = i + 1; j < l; j++){
		                	if(data.list[i]["vao15"].trim() == data.list[j]["vao15"].trim()){
		                		x+=1;
		                		break;
		                	} 
		                	
		                }
		                if(x==0 && list.length<31){
		                list.push(data.list[i]);
		                }
		            }
				
				
//				for(var i = 0;i<data.list.length; i++){
//					var vao15 = data.list[i]["vao15"];
//	                for(var j = i + 1; j < data.list.length; j++){
//	                	if(vao15.trim() == data.list[j]["vao15"].trim()){
//	                		delete data.list[i];
//	                	} 
//	                }
//	            }
				that.laytplUrl(myurl+"/module/changyongzhenduan.html",list,function(data,html){
					$("#changyongContent").html(html);
				});
			}
		});
}
//中药参考
function zhongyaocankao(id){
	rightTab = id;
	var that = this;
			that.laytplUrl(myurl+"/module/zhongyao_cankao.html",{},function(data,html){
				$("#changyongContent").html(html);
				//加载中药参考树
				$.ajax({
					url: rootUrl+"/doctoradviceeditor/treelist",
					type: "get",
					data:{"lBEH01":'3',"BCE01":bce01,"BCK01":bck01},
					dataType:'json',
					success:function(data)
					{
						var list = data.list;
						$('#zyck_tree').treeview({data: list});
						$('#zyck_tree').on('nodeSelected', function(event, data) {
							// 加载点击数节点数据
							zhongyaocank_tree_list("1",data["bdo01"],curr);
							});
					}
				});
			});
}
//树节点数据
function zhongyaocank_tree_list(lBDA01,lBDO01,curr)
{
	var  bad01 = "('3')";
	$.ajax({
		url: rootUrl+"/doctoradviceeditor/medtreetodetail",
		type: "get",
		data:{"lBDO01":lBDO01,"lBDA01":lBDA01,"lACF01":1,"lSql":'%',"lBBX09":1,"BCKyf":0,"vaf58":0,"bda01":bad01,
			"lBEH01":1,"lBCE01":bce01,"lBCK01":bck01,"abc02":"医保","bdp02":"医保","BCKyf":0,currPage:curr,pageSize:pageSize},
		dataType:'json',
		success:function(data)
		{
			var list = data.list;
			var $xiangxixiangmu = $("#zyck_tree_table");
			// append性能低，改为laytpl模板加载
			laytplUrl(myurl+"/module/tree-table-zhongyaocankao.html",data,function(data,html){
				$xiangxixiangmu.empty().append(html);
				  var pages=parseInt(data.total)%parseInt(pageSize);
			        if(pages==0){
			        	totalPage=parseInt(data.total) / parseInt(pageSize);
			        }else{
			        	totalPage=parseInt(data.total-pages) /parseInt(pageSize) + 1
			        }
				laypage({
		            cont: 'zyck_page', 
		            pages:totalPage, 
//		            skip: true, //是否开启跳页
//		            skin: '#33b818',
		            groups: 3, //连续显示分页数
		            curr: curr || 1, 
		            jump: function(obj, first){ 
		                if(!first){ 
		                	zhongyaocank_tree_list(lBDA01,lBDO01,obj.curr);
		                }
		            }
		        });
			});
		}
	});

	
}
/*诊断下拉框*/
function xySelectDiv(){
	$(".bootstrap-tagsinput").on("click",function(){
		 var e=arguments.callee.caller.arguments[0]||event; 
		 if (e && e.stopPropagation) { 
		  // this code is for Mozilla and Opera
		  e.stopPropagation(); 
		 } else if (window.event) { 
		  // this code is for IE 
		  window.event.cancelBubble = true; 
		 } 
		 if($("#neworder_zhenduan").is(":visible")){
			 return;
		 }
		var thisLeft=$(this).offset().left;
		var thisTop=$(this).offset().top;
		var thisheight=$(this).outerHeight()+1;
		$(".selectDiv").slideDown();
		$(".selectDiv").css({
			position:"absolute",
			left:thisLeft,
			top:thisTop+thisheight+"px",
			display:"block"
		})
		$("#refund").css({
			"z-index":999
		})
		addChangyongzhenduan();
		keySearchJibingEvent();//疾病搜索
//		selfDiagnoseEvent('show'); //自定义诊断
//		hideDiv(".selectDiv");
	})
}
//诊断数据加载
function addChangyongzhenduan(){
	//加载疾病
	/*var url = rootUrl+"/treatment/jibingList";
	var params = {};
	debugger;
	$.ajax({url:url,data:params,dataType:'json',type:'get', success:function(data){
		var list = data.list;
	}});*/
	$('#jibing-tree').treeview({data: parent.jibingList});
	$('#jibing-tree').on('nodeSelected', function(event, data) {
		$("#search_jibing").val('');
		// 查询疾病详细项目列表
		xiangxiList(data['id']);
	});
	var data=bingrenVaoList;
	if(data.length>0){
		laytplUrl(myurl+"/module/zhenduan_table.html",data,function(data,html){
			$("#xydqzd").empty().append(html);
			
		});
	}else{
		data={};
		laytplUrl(myurl+"/module/wulishizhenduan_table.html",data,function(data,html){
			$("#xydqzd").html(html);
		});
	}
	
}

//诊断疾病-根据cag01查询详细
function xiangxiList(bah01)
{
	var url = rootUrl+"/treatment/jibingInfo";
	var params = {};
	params.bah01 = bah01;
	$.get(url,params,function(data){
		if(data){
			debugger;
			laytplUrl(myurl+"/module/tree-table-jibing.html",data,function(data,html){
				$("#jibing-tree-table").empty().append(html);
				$(".selectDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
			});
		}
	});
}
//诊断疾病搜索
function searchJibingEvent(){
//	layer.msg('查询中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500});  
	var text = $("#search_jibing").val();
	var reg= /^[A-Za-z]+$/; //判断是字母
	if (reg.test(text)){
		text = text.toLowerCase();
	}
	var url1 = solrUrl + "/menzhenzhenduan";
	var params={};
	params.q = "(bak02:*"+text+"* OR bak05:*"+text+"* OR bak06:*"+text+"* OR abbrp:*"+text+"* OR abbrw:*"+text+"*)";
	params.fl = 'bak01,bak02,bak05,bak06,abbrp,abbrw,abw01,cam01';
	params.url = url1;
	params.rows = 30;
	var params1={};
	params1.q = "(bak02:"+text+" OR bak05:"+text+" OR bak06:"+text+" OR abbrp:"+text+" OR abbrw:"+text+")";
	params1.fl = 'bak01,bak02,bak05,bak06,abbrp,abbrw,abw01,cam01';
	params1.url = url1;
	params1.rows = 1;
	$.ajax({
		url : rootUrl+"/doctoradvice/queryAdviceBySolr",
		type : "post",
		dataType : 'json',
		data:{params:JSON.stringify(params1)},
		success : function(data) {
			debugger;
			var list1;
			if(data.list && data.list.length>0)
			{
				list1 = data.list;
			}
			$.ajax({
				url : rootUrl+"/doctoradvice/queryAdviceBySolr",
				type : "post",
				dataType : 'json',
				data:{params:JSON.stringify(params)},
				success : function(data) {
					if(data.list && data.list.length>0){
						if (list1 && list1.length>0)
						{
							data.list = $.merge(list1, data.list);
						}
						laytplUrl(myurl+"/module/tree-table-jibing-search.html",data,function(data,html){
							$("#jibing-tree-table").empty().append(html);
							$(".selectDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
						});
					}else{
						$("#jibing-tree-table").empty();
					}
				}
			});
		}
	});
}
//诊断疾病回车搜索
function keySearchJibingEvent(){ 
	$("#search_jibing").on("input",function(){
		searchJibingEvent();
	})
	
}

//右侧常用诊断双击到诊断标签
function xiaDaZhenDuan(vao15,vao01){
	 var str = '{"bak01a":"'+vao01+'"}';
	$("#diagnose_tip").tagsinput('add',vao15,str);
}


function closeChangeTdDiv_zhenduan(){
	$("#neworder_zhenduan").hide();
}
//input输入事件事件
function inputEvent(id){
	var currentInput=$("#"+id).focus();
	/*按回车按钮后弹出下拉框*/
//	currentInput.keydown(function (e) {
//	var inputText=$(this).val();
//      if (e.which === 13&&($(".smart_search").attr("style"))&&($(".smart_search").attr("style").indexOf("block")<0)) {
//      	var that=this;
//      	$("#cover").removeClass("hidden");
//      	getDropList(id,inputText);
//      }
//      });
	
//	$("#"+id).on("dblclick",function(){//点击出现下拉
//		$("#cover").removeClass("hidden");
//		var inputText=$(this).val();
//		getDropList(id,inputText);
//	})
	$("#"+id).parents("tr").find(".btn-drop").off("click").on("click",function(){//点击出现下拉
		debugger;
		$("#cover").removeClass("hidden");
		var inputText=$(this).val();
		var reg= /^[A-Za-z]+$/; //判断是字母
		if (reg.test(inputText)){
			inputText = inputText.toLowerCase();
		}
		adviceItemEvent(id);
//		getDropList(id,inputText);
	})
//	$("#"+id).focus(function(){//点击出现下拉
//		$("#cover").removeClass("hidden");
//		var inputText=$(this).val();
//		addSmartSearch(id);
//	})
	//智能搜索input事件
	$("#" +id).advicesmart({id:"smart_advice"});
//	$("#" +id).on("keyup", function(e)
//	{
//		 var e = event || window.event || arguments.callee.caller.arguments[0];
//         if(e && e.keyCode!=13 &&e.keyCode!=40 &&e.keyCode!=38&&e && e.keyCode!=120){
////        	 $("#cover").removeClass("hidden");
//        	 //input 框失去焦点
//        	 if(e.keyCode!=32)
//             {
//            	 $("#"+id).next().val("");
//             }
//        	 addSmartSearch(id);
//        	 
//         }
//        
//         
//	});
}

//西药同组要用。
function clickSaveActiveAdviceInputId(id){
	$("#"+id).on("click",function(){
		activeAdviceInputId = id;
	})
}
/* 点击出现下拉框 */
function getDropList(inputId,inputText){
	closeSelfLayer();
	$("#tree-table").empty();
	$("#tree_page").empty();
	$("#search_page").hide();
		activeAdviceInputId = inputId;// 更新激活当前激活的input框ID
        var flagTop = $("#"+inputId).parent().position().top;
        if(flagTop >0){
        	// css
        	var thiswidth=$("#"+inputId).parent().outerWidth();
        	var thisLeft=$("#"+inputId).parent().offset().left+30;
        	var thisTop=188;
//        	var thisheight=$("#"+inputId).parent().outerHeight()+1;
        	$(".changeTdDiv").slideDown();
        	$(".changeTdDiv").css({
//        		position:"absolute",
        		left:thisLeft+thiswidth,
        		top:thisTop+"px",
        		transform: "none",
        		display:"block"
        	})
        	$("#refund").css({
        		"z-index":999
        	})

        }else{
        	
        	// css
        	var thisLeft=$("#"+inputId).parent().offset().left;
        	var thisTop=$("#"+inputId).parent().offset().top;
        	var thisheight=$("#"+inputId).parent().outerHeight()+1;
        	$(".changeTdDiv").slideDown();
        	$(".changeTdDiv").css({
//        		position:"absolute",
        		left:thisLeft,
        		top:thisTop+thisheight+"px",
        		transform: "none",
        		display:"block"
        	})
        	$("#refund").css({
        		"z-index":999
        	})
        }
        	$("#search_medicine").focus();
			$("#search_medicine").val(inputText);//搜索框赋值
			var pass= {};
			pass.inputId = inputId;
			pass.sqltext = inputText; //新开医嘱
			pass.item = 'aitem'; //新开医嘱
			adviceSousuo(pass);
			huicheSearch(pass); //搜索框回车事件
			// load tree
			// 构造树形结构json
			var lbeh01 = configBeh01();
//			var lbeh01 = initGloableParams();
			debugger;
			$.ajax({
				url: rootUrl+"/doctoradviceeditor/treelist",
				type: "get",
				data:{"lBEH01":lbeh01,"BCE01":bce01,"BCK01":bck01},
				dataType:'json',
				success:function(data)
				{
					debugger;
					var list = data.list;
					$('#tree').treeview({data: list});
					
					selectBotstrapTree(pass);
					
				}
			});
		
//	})
}


function huicheSearch(pass){
	$("#search_medicine").keydown(function (e) {
      if (e.which === 13) {
    	  changeBbx1(pass)
      }
      });
	$("#changeBbx1").on("click",function(){
		changeBbx1(pass)
	})
}

//树节点选中事件
function selectBotstrapTree(pass){
	$('#tree').off('nodeSelected').on('nodeSelected', function(event, data) {
//		$("#"+activeAdviceInputId).val('');
		$("#search_medicine").val('');
		  // 查询详细项目列表
		  pass.bdo01 = data["bdo01"];
		  pass.curr = curr;
		  pass.bdm01 = data["bdm01"];
		  pass.bdm01 = data["bdm01"];
		  if(topTab=="Xiyao")
		  {
			  pass.lbda01 = "1";
			  // 查询西药品信息
			  yaopinList(pass);
//			  yaopinList("1",data["bdo01"],pass.inputId,curr,data["bdm01"]);
		  }
		  else if(topTab=="Zhongyao")
		  {
			  // 查询中药品信息
			  pass.lbda01 = "3";
			  yaopinList(pass);
//			  yaopinList("3",data["bdo01"],pass.inputId,curr,data["bdm01"]);
		  }
		  else
		  {
			  // 查询其它项目信息
			  otherList(pass);
		  }
		});
}
/**
 * 根据首字母检索对应类型医嘱
 */
function adviceSousuo(pass)
{
	offset = 0;
	adviceSousuo_public(pass)
}

/**
 * 搜索医嘱调用
 * @param sqltext
 */

function adviceSousuo_public(pass)
{
	var sqltext = pass.sqltext;
	$("#getBack").attr("disabled",true);
	$("#getNext").attr("disabled",true);
	var params = {};
	pass.item = 'aitem'; //新开医嘱
	if (sqltext!='') {
		var beh01;
		switch (topTab) {
		case "Xiyao":
			beh01 = "1";params.bckyf = valueArr.p_100_105002_108;
			break;
		case "Zhongyao":
			beh01 = "3";params.bckyf = valueArr.p_100_105002_110;
			break;
		case "Jianyan":
			beh01 = "5";params.bckyf = 0;
			break;
		case "Jiancha":
			beh01 = "4";params.bckyf = 0;
			break;
		case "Shoushu":
			beh01 = "6";params.bckyf = 0;
			break;
		case "Zhiliao":
			beh01 = "7";params.bckyf = 0;
			break;
		case "Cailiao":
			beh01 = "8";params.bckyf = valueArr.p_100_105002_404;
			break;
		}
		var url = rootUrl + "/clischemedefine/adviceSousuo";
		
		params.sqltext = '%' + sqltext + '%';
		params.acf01 = 1;
		params.bbx09 = 1;
		params.beh01 = beh01;
		params.bck01 = bck01;
		params.bce01 = bce01;
		params.abc02 = '普通';
		params.bdp02 = '自费';
		params.vaf58 = 0;
		params.yiyuanId = yiyuanId;
		params.offset = offset;
		$.get(url, params, function(data) {
			var $xiangxixiangmu = $("#tree-table");
			$("#tree_page").hide();
			$("#search_page").show();
			if(data.list.length > 0){
				data.item= pass.item;
				// append性能低，改为laytpl模板加载
				if((topTab=="Xiyao")||(topTab=="Zhongyao")||(topTab=="Cailiao")){
					laytplUrl(myurl + "/module/tree-table-yaopin.html", data,
							function(data, html) {
						$xiangxixiangmu.empty().append(html);
//							$(".changeTdDiv").find("table tbody tr:eq(0)").trigger("focus");
						$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
					});
				}else{
					laytplUrl(myurl + "/module/tree-table-feiyaopin.html", data,
							function(data, html) {
						$xiangxixiangmu.empty().append(html);
//							$(".changeTdDiv").find("table tbody tr:eq(0)").trigger("focus");
						$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
					});
				}
			}else{
				$xiangxixiangmu.empty().append("<tr><td>无匹配数据</td></tr>");
			}
			$("#getBack").attr("disabled",false);
			$("#getNext").attr("disabled",false);
			//按钮状态处理
			//禁止上一步按钮
			if(offset==0)
			{
				$("#getBack").attr("disabled",true);
				$("#getNext").attr("disabled",false);
				if(!data || data.list.length<10)
				{
					$("#getBack").attr("disabled",true);
					$("#getNext").attr("disabled",true);
				}
			}
			else
			{
				$("#getBack").attr("disabled",false);
				$("#getNext").attr("disabled",false);
				if(!data || data.list.length<10)
				{
					$("#getBack").attr("disabled",false);
					$("#getNext").attr("disabled",true);
				}
			}
			
			
			
			
		});
	}
}

//医嘱搜索不分页，每次显示10条数据
function adviceSearchEvent(type){ //
	debugger;
	var pass = {};
	var sousuoText = $("#search_medicine").val();
	var reg= /^[A-Za-z]+$/; //判断是字母
	if (reg.test(sousuoText)){
		sousuoText = sousuoText.toLowerCase();
	}
	pass.sqltext = sousuoText;
	if(type==0)
	{
		offset = 0;
		adviceSousuo_public(pass);
	}
	else if(type==-1)
	{
		offset -= 10;
		adviceSousuo_public(pass);
	}
	else if(type==1)
	{
		offset += 10;
		adviceSousuo_public(pass);
	}
}
function configBeh01()
{
	var lbeh01 = "5";
	if(topTab=="Xiyao")
	{
		lbeh01 = "1";
	}
	else if(topTab=="Zhongyao")
	{
		lbeh01 = "3";
	}
	else if(topTab=="Jiancha")
	{
		lbeh01 = "4";
	}
	else if(topTab=="Jianyan")
	{
		lbeh01 = "5";
	}
	else if(topTab=="Shoushu")
	{
		lbeh01 = "6";
	}
	else if(topTab=="Zhiliao")
	{
		lbeh01 = "7";
	}
	else if(topTab=="Cailiao")
	{
		lbeh01 = "8";
	}
	return lbeh01;
}

// 加载tree-table内容(药品)
//yaopinList("1",data["bdo01"],pass.inputId,curr,data["bdm01"]);
function yaopinList(pass)
{
	debugger;
	var lBDA01 = pass.lbda01,lBDO01 =pass.bdo01 ,inputId=pass.inputId,curr = pass.cur,bdm01=pass.bdm01;
	var bda01 = "";
	var bckyf = 0;
	switch(topTab)
	 {
	 	case "Xiyao" : bda01 = "('1','2')"; bckyf = valueArr.p_100_105002_108;break;
	 	case "Zhongyao" : bda01 = "('3')"; bckyf = valueArr.p_100_105002_110;break;
	 }
	$.ajax({
		url: rootUrl+"/doctoradviceeditor/medtreetodetail",
		type: "get",
		data:{"lBDO01":lBDO01,"lBDA01":lBDA01,"lACF01":1,"lSql":'%',"lBBX09":1,"BCKyf":0,"vaf58":0,"bda01":bda01,bdm01:bdm01,"yiyuanId":yiyuanId,
			"lBEH01":'3',"lBCE01":bce01,"lBCK01":bck01,"abc02":$("#abc02").text(),"bdp02":$("#patient_bdp02").text(),"BCKyf":bckyf,currPage:pass.curr,pageSize:pageSize},
		dataType:'json',
		success:function(data)
		{
			debugger;
			data.bdm01 = bdm01;
			var list = data.list;
			$("#tree_page").show();
			$("#tree_page").empty();
			$("#search_page").hide();
			var $xiangxixiangmu = $("#tree-table");
			if(list.length > 0){
				data.item= pass.item;
				// append性能低，改为laytpl模板加载
				laytplUrl(myurl+"/module/tree-table-yaopin.html",data,function(data,html){
					$xiangxixiangmu.empty().append(html);
//				$(".changeTdDiv").find("table tbody tr:eq(0)").trigger("focus");
					$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
					var pages=parseInt(data.total)%parseInt(pageSize);
					if(pages==0){
						totalPage=parseInt(data.total) / parseInt(pageSize);
					}else{
						totalPage=parseInt(data.total-pages) /parseInt(pageSize) + 1
					}
					laypage({
						cont: 'tree_page', 
						pages:totalPage, 
//		            skip: true, //是否开启跳页
//		            skin: '#33b818',
						groups: 5, //连续显示分页数
						curr: pass.curr || 1, 
						jump: function(obj, first){ 
							if(!first){ 
								pass.curr = obj.curr;
								yaopinList(pass);
							}
						}
					});
				});
			}else{
				$xiangxixiangmu.empty().append("<tr><td>暂无数据</td></tr>");
			}
		}
	});
}
// 加载tree-table内容（非药品）
function otherList(pass)
{
	var lBDO01 =pass.bdo01 ,inputId=pass.inputId,curr = pass.cur;
	var bad01; 
	var beh01;
	switch(topTab)
	 {
	 	case "Jianyan" : bad01 = "L"; beh01="5"; break;
	 	case "Jiancha" : bad01 = "E"; beh01="4"; break;
	 	case "Shoushu" : bad01 = "S"; beh01="6"; break;
	 	case "Zhiliao" : bad01 = "T"; beh01="7"; break;
	 	case "Cailiao" : bad01 = "4"; beh01="8"; break;
	 }
	var bckyf = valueArr.p_100_105002_404;
	$.ajax({
		url: rootUrl+"/doctoradviceeditor/classificationretrieval",
		type: "post",
		data:{"lBDO01":lBDO01,"lACF01":1,"lSql":'%',"lBBX09":1,"lBEH01":beh01,"lBCE01":bce01,"lBCK01":bck01,"yiyuanId":yiyuanId,
			"abc02":$("#abc02").text(),"bdp02":$("#patient_bdp02").text(),"BCKyf":bckyf,"productId":9999,"programId":9999,"paramNo":60,"lbda01":bad01,currPage:pass.curr,pageSize:pageSize},
		dataType:'json',
		success:function(data)
		{
			var list = data.list;
			$("#tree_page").show();
			$("#tree_page").empty();
			$("#search_page").hide();
			var $xiangxixiangmu = $("#tree-table");
			if(list.length){
				data.item= pass.item;
				var muban = "/module/tree-table-feiyaopin.html";
				debugger;
				if(topTab=="Cailiao")
				{
					muban = "/module/tree-table-yaopin.html";
				}
				laytplUrl(myurl+muban,data,function(data,html){
					$xiangxixiangmu.empty().append(html);
//				$(".changeTdDiv").find("table tbody tr:eq(0)").trigger("focus");
					$(".changeTdDiv").find("table tbody tr:eq(0)").addClass("choseedTr");
					var pages=parseInt(data.total)%parseInt(pageSize);
					if(pages==0){
						totalPage=parseInt(data.total) / parseInt(pageSize);
					}else{
						totalPage=parseInt(data.total-pages) /parseInt(pageSize) + 1
					}
					laypage({
						cont: 'tree_page', 
						pages:totalPage, 
//		            skip: true, //是否开启跳页
//		            skin: '#33b818',
						groups: 5, //连续显示分页数
						curr: pass.curr || 1, 
						jump: function(obj, first){ 
							if(!first){ 
								pass.curr = obj.curr;
								otherList(pass);
							}
						}
					});
				});
			}else{
				$xiangxixiangmu.empty().append("<tr><td>暂无数据</td></tr>");
			}
		}
	});
	
}
function otherListT(lBDO01)
{
	var bad01; 
	var beh01;
	debugger;
	$.ajax({
		url: rootUrl+"/doctoradviceeditor/classificationretrieval_fangan",
		type: "post",
		data:{"lBDO01":lBDO01,"lACF01":1,"lSql":'%',"lBBX09":1,"lBEH01":"9","lBCE01":bce01,"lBCK01":bck01,
			"abc02":$("#abc02").text(),"bdp02":$("#bdp02").text(),"productId":9999,"programId":9999,"paramNo":60,"lbda01":"9"},
			dataType:'json',
			success:function(data)
			{
				var list = data.list;
				var $xiangxixiangmu = $("#tree-tableT");
				// append性能低，改为laytpl模板加载
				laytplUrl(myurl+"/module/tree-table-zhiliaofangan.html",data,function(data,html){
					$xiangxixiangmu.empty().append(html);
				});
			}
	});
	
}

function zhiliaoKeyUp(){
	$("#fanganjiansuoText").on("keyup", function(e)
	{
		debugger;
		var e = event || window.event || arguments.callee.caller.arguments[0];
		if(e && e.keyCode ==13 ){
			layer.msg('查询中....', {icon: 16,shade: [0.1, '#393D49'],time:1*500,skin: 'layui-layer-msg16'});
			getPersonalFangan1(1,'fanan_keshi');
		}
	});
}
//治疗方案检索
function jiansuoFangan()
{
	debugger;
	var text = $("#fanganjiansuoText").val();
	$.ajax({
		url: rootUrl+"/doctoradviceeditor/jiansuoFangan",
		type: "post",
		data:{"lACF01":1,"lSql":'%'+text+'%',"lBBX09":1,"lBEH01":"9","lBCE01":bce01,"lBCK01":bck01,
			"abc02":$("#abc02").text(),"bdp02":$("#bdp02").text(),"lbda01":"9"},
			dataType:'json',
			success:function(data)
			{
				debugger;
				var list = data.list;
				var $xiangxixiangmu = $("#tree-tableT");
				// append性能低，改为laytpl模板加载
				laytplUrl(myurl+"/module/tree-table-zhiliaofangan.html",data,function(data,html){
					$xiangxixiangmu.empty().append(html);
				});
			}
	});
}

// 界面所有select框值加载
function loadAllSelectVal()
{
	//计价性质
	jijiaxingzhiListHtml = "<select >";
	jijiaxingzhiListHtml += "<option value='0'>正常</option>";
	jijiaxingzhiListHtml += "<option value='1'>自费</option>";
	jijiaxingzhiListHtml += "</select>";
	// 执行性质
	var url1 = rootUrl+"/doctoradvice/doctoradviceexecuteproperty";
	var params1 = {};
	params1.asign = 0;
	// 中药煎法
	var url2 = rootUrl+"/clischemedefine/findspecialtreament";
	var params2 = {};
	params2.lBDA01 = 'T';
	params2.lBBX13 = '3';
	// 检验样本
	var url3=rootUrl+"/doctoradviceeditor/yangben" ;
	var params3={} ;
	var url4 = rootUrl+"/clinewadvice/getOperationpro";	// 手术附加项目
	var url5 = rootUrl+"/clinewadvice/getAnaesthesiaItem";	// 手术麻醉项目
	//病人常用诊断
	var url8 = rootUrl+"/treatment/querypatienttreatmentrecord";
	var params8 = {};
	params8.vaa01 = vaa01;
	params8.acf01 = 1;
	params8.vaa07 = vac01;
	params8.currPage = 1;
	params8.pageSize = 10;
	// 用药目的
	var url6 = rootUrl+"/clinewadvice/getYongyaomudiList";
	
	var url9 = rootUrl+"/basicinformationquery/zhixingkeshi1";
	//其它医嘱频次
	var url20 = rootUrl+"/treatment/otherPinci";
	//手术人员列表
	var url7 = rootUrl+"/clinewadvice/shoushurenyuanList";
	//给药执行
	var url21 = rootUrl+"/treatment/geiyaokeshiList";
	var url13 = rootUrl+"/clidoctor/queryBce1Info";
	var params13 = {};
	params13.bck01 = bck01;
	var url14 = rootUrl+"/clidoctor/aab1";
	var urlCom = rootUrl+"/basicinformationquery/basequery";
	var param14 = {params:JSON.stringify({sqlId:10000041})};
	var url15 = rootUrl + "/basicinformationquery/basequery";
	var param15 = {params:JSON.stringify({sqlId:10000046,bck01:bck01,yiyuanid:yiyuanId})};
	$.when(
	//中药加载执行科室--10000046 
	$.ajax({
		url:url15,
		type: "get",
		data:param15,
		dataType:'json',
		async: true,
		success:function(data)
		{
			debugger;
			var list = data.list;
			zyzhixingkeshi46 = "<select class='zyzhixingkeshi46' onchange='isOutHospital();'>";
			for(var j = 0;j<list.length;j++)
			{
				if( list[j]["bck01b"] == valueArr['p_100_105002_110']){
					zyzhixingkeshi46 = zyzhixingkeshi46 + "<option  value='"+list[j]["bck01b"]+"' selected='selected'>";
				}else{
					zyzhixingkeshi46 = zyzhixingkeshi46 + "<option  value='"+list[j]["bck01b"]+"'>";
				}
				zyzhixingkeshi46 = zyzhixingkeshi46 +  list[j]["bck03"];
				zyzhixingkeshi46 = zyzhixingkeshi46 +  "</option>";
			}
			zyzhixingkeshi46 += "</select>";
			
		}
	}),
	//项目归属-10000041
	$.ajax({
		url:urlCom,
		type: "get",
		data:param14,
		dataType:'json',
		async: true,
		success:function(data)
		{
			var xiangmuguishuList = data.list;
			xiangmuguishuHtml += "<option value=''>请选择</option>";
			for(var j = 0;j<xiangmuguishuList.length;j++)
			{
				xiangmuguishuHtml += "<option value='"+xiangmuguishuList[j]['bgz01']+"'>"+xiangmuguishuList[j]['bgz02']+"</option>";
			}
			$(".xmgs").empty().append(xiangmuguishuHtml);
		}
	}),
	// 西药给药途径 -16776
	$.ajax({
		url:urlCom,
		type: "get",
		data:{params:JSON.stringify({sqlId:10000048,bce01:bce01,bck01:bck01})},
		dataType:'json',
		async: true,
		success:function(data)
		{
			var geiyaotujingList = data.list;
			geiyaoHtml = "<select class='geiyaoHtml' onchange='getGeiyaoZhixing(this)'>";
			for(var j = 0;j<geiyaotujingList.length;j++)
			{
				geiyaoHtml = geiyaoHtml + "<option id='"+geiyaotujingList[j]["bbx01"]+"' name='"+geiyaotujingList[j]["bbx01"]+"' value='"+geiyaotujingList[j]["bbx01"]+"' data-info='"+JSON.stringify(geiyaotujingList[j])+"'>";
				geiyaoHtml = geiyaoHtml +  geiyaotujingList[j]["bbx05"];
				geiyaoHtml = geiyaoHtml +  "</option>";
			}
			geiyaoHtml += "</select>";
		}
	}),
	// 西药诊疗频次
	$.ajax({
		url:rootUrl+"/clinewadvice/zhenLiaoPinCiList",
		type: "get",
		data:{"lbdi10":1},
		dataType:'json',
		success:function(data)
		{
			var zhenLiaoPinCiList = data.list;
			zhenLiaoPinCiHtml = "<select class='zhenLiaoPinCiHtml'  onchange='jisuanZongliang(this)'>";
			for(var k = 0;k<zhenLiaoPinCiList.length;k++)
			{
				zhenLiaoPinCiHtml = zhenLiaoPinCiHtml + "<option id='"+zhenLiaoPinCiList[k]["bdi06"]+"' name='"+
				zhenLiaoPinCiList[k]["bdi08"]+"' value='"+zhenLiaoPinCiList[k]["bdi01"]+"' data-bdi03='"+zhenLiaoPinCiList[k]["bdi03"]+"'>";
				zhenLiaoPinCiHtml = zhenLiaoPinCiHtml + zhenLiaoPinCiList[k]["bdi02"];
				zhenLiaoPinCiHtml = zhenLiaoPinCiHtml + "</option>";
			}
			zhenLiaoPinCiHtml += "</select>";
		}
	}),
	// 执行性质
	
	$.post(url1,params1,function(data)
			{
				var list = data.list;
				zhiXingXingZhiHtml = "<select class='zhiXingXingZhiHtml'>";
				for(var k = 0;k<list.length;k++)
				{
					zhiXingXingZhiHtml += "<option id='"+list[k]["fid"]+"' value='"+list[k]["fid"]+"'>";
					zhiXingXingZhiHtml += list[k]["fname"];
					zhiXingXingZhiHtml += "</option>";
				}
				zhiXingXingZhiHtml += "</select>"; 
			}),
	// 门诊部门
	$.ajax({
		url: rootUrl+"/patientsearch/finddepartments",
		type: "get",
		dataType:'json',
		data:{"bce01":bce01,"bck01":$(window.parent.document).find("#hospital").val()},
//		data:{"bce01":bce01,"bck01":bck01},
		success:function(data){
			departmentList = data.list;
			var kaidankeshi = $("#kaidankeshi").val();
			bck01ListHtml="<select class='bck01ListHtml'>";
			for(var i = 0; i<departmentList.length; i++)
			{
				if(departmentList[i]["bck01"]==kaidankeshi)
				{
					bck01ListHtml += "<option value=\""+departmentList[i]["bck01"]+"\" selected=selected>" + departmentList[i]["bck03"] + "</option>";
				}
				else
				{
					bck01ListHtml += "<option value=\""+departmentList[i]["bck01"]+"\">" + departmentList[i]["bck03"] + "</option>";
				}
			}
			bck01ListHtml += "</select>";
		}
		}),
	// 中药频次
	$.ajax({
		url:rootUrl+"/clinewadvice/zhenLiaoPinCiList",
		type: "get",
		data:{"lbdi10":2},
		dataType:'json',
		success:function(data)
		{
			var zhenLiaoPinCiList = data.list;
			zhenLiaoPinCiHtml2 = "<select class='zhenLiaoPinCiHtml2'>";
			for(var k = 0;k<zhenLiaoPinCiList.length;k++)
			{
				zhenLiaoPinCiHtml2 = zhenLiaoPinCiHtml2 + "<option value='"+zhenLiaoPinCiList[k]["bdi06"]+"',name='"+
				zhenLiaoPinCiList[k]["bdi01"]+"',id='"+zhenLiaoPinCiList[k]["bdi08"]+"' data-bdi03='"+zhenLiaoPinCiList[k]["bdi03"]+"'>";
				zhenLiaoPinCiHtml2 = zhenLiaoPinCiHtml2 + zhenLiaoPinCiList[k]["bdi02"];
				zhenLiaoPinCiHtml2 = zhenLiaoPinCiHtml2 + "</option>";
			}
			zhenLiaoPinCiHtml2 += "</select>";
		}
	}),
	// 加载中药脚注
	$.get(rootUrl+"/clinewadvice/zhongyaoJiaozhu",{},function(data){
		var list = data.list;
		zhongyaojiaozhuHtml = "<select class='zhongyaojiaozhuHtml'>";
		zhongyaojiaozhuHtml += "<option value='-1'>请选择</option>"
		for(var i = 0;i<list.length;i++)
		{
			zhongyaojiaozhuHtml += "<option value='"+list[i]["acx01"]+"'>";
			zhongyaojiaozhuHtml += list[i]["acx02"];
			zhongyaojiaozhuHtml += "</option>";
		}
		zhongyaojiaozhuHtml += "</select>";
	}),
	// 中药煎法
	$.post(url2,params2,function(data){
		var list = data.list;
		zhongyaojianfaHtml = "<select class='zhongyaojianfaHtml' onchange='zygetGeiyaoZhixing();'>";
		for(var i = 0;i<list.length;i++)
		{
			zhongyaojianfaHtml += "<option value='"+list[i]["bbx01"]+"'>";
			zhongyaojianfaHtml += list[i]["bbx05"];
			zhongyaojianfaHtml += "</option>";
		}
		zhongyaojianfaHtml += "</select>";
	}),
	// 中药用法
	$.get(rootUrl+"/clinewadvice/zhongyaoyongfa",{},function(data)
		{
			var yfList = data.list;
			zhongyaoyongfaHtml = "<select class='zhongyaoyongfaHtml'>";
			for(var i = 0;i<yfList.length;i++)
			{
				zhongyaoyongfaHtml += "<option value='"+yfList[i]["bbx01"]+"'>";
				zhongyaoyongfaHtml += yfList[i]["bbx05"];
				zhongyaoyongfaHtml += "</option>";
			}
			zhongyaoyongfaHtml += "</select>";
		}),
	// 检验样本
	$.get(url3,params3,function(data)
			{
			// 样本列表
			yangbenList = data.list;
			jyyangbenleixing = "<select class='jyyangbenleixing'>";
			for(var j = 0; j<yangbenList.length; j++)
			{
				jyyangbenleixing += "<option value='"+yangbenList[j]['abb01']+"' >"+yangbenList[j]['abb02']+"</option>";
			}
			jyyangbenleixing += "</select>";
			}

	),
	$.get(url4, function (resp) {
		if (resp.result == 'Success') {
			var rList = resp.list;
			if (rList.length) {
				fujianshoushuListHtml = "<select class='fujianshoushuListHtml form-control'>";
				for (var i = 0; i < rList.length; i++) {
					var id = rList[i].bda01+'|'+rList[i].bbx01 + '|' + rList[i].bbx04 + "|";
					var txt = rList[i].bbx05 + "|" + (rList[i].bdg02 == undefined ? "" : rList[i].bdg02) + "|" + (rList[i].ach02 == undefined ? "" : rList[i].ach02);
					fujianshoushuListHtml += "<option id='"+id+"'>"+txt+"</option>";
				}
				fujianshoushuListHtml += "</select>";
			}
		}
	}),
	$.get(url5, function (resp) {
		if (resp.result == 'Success') {
			var rList = resp.list;
			mazuiHtml +='<select>';
			mazuiHtml +='<option value="">无麻醉</option>'
			if (rList.length) {
					 for(var i=0;i<rList.length;i++){
							var id = (rList[i].bda01==undefined?0:rList[i].bda01)+'|'+rList[i].bbx01;
							 mazuiHtml +='<option  value='+id+'>'+rList[i].bbx05+'</option>'
//							mazuiHtml += '<div class="radio"><label >';
//							mazuiHtml += '<input type="radio" name="mz" style=" position: relative;"  value='+id+'><span>';
//							mazuiHtml += rList[i].bbx05;
//							mazuiHtml += '</span></label></div>';
						}
//				  mazuiHtml +='<div class="radio"><label ><input type="radio" name="mz" style=" position: relative;" value="" checked ><span>无麻醉</span></label></div>';
//				for(var i=0;i<rList.length;i++){
//					var id = (rList[i].bda01==undefined?0:rList[i].bda01)+'|'+rList[i].bbx01;
//					mazuiHtml += '<div class="radio"><label >';
//					mazuiHtml += '<input type="radio" name="mz" style=" position: relative;"  value='+id+'><span>';
//					mazuiHtml += rList[i].bbx05;
//					mazuiHtml += '</span></label></div>';
//				}
			}
			mazuiHtml +='</select>'
		}
	}),
	// 用药目的
	$.get(url6,function(data)
			{
		  var list = data.list;
		  yongyaomudiHtml = "<select class='yongyaomudiHtml'>";
			for(var i = 0;i<list.length;i++){
				yongyaomudiHtml += "<option value="+list[i]["biw01"]+">"+list[i]["biw02"]+"</option>";
			}
			yongyaomudiHtml += "</select>";
			
			
			}),
	//手术人员列表
	$.get(url7,function(data)
			{
				var list = data.list;
				shoushurenyuanHtml = "<select class='shoushurenyuanHtml'>";
				shoushurenyuanHtml+='<option value="">--请选择--</option>';
				for(var i = 0;i<list.length;i++)
				{
					shoushurenyuanHtml += "<option id='"+list[i]["bce02"]+"' value='"+list[i]["bce01"]+"'>"+list[i]["bce03"]+"</option>";
				}
				shoushurenyuanHtml += "</select>";
			}),
	//病人常用诊断
	$.ajax({url:url8,data:params8,dataType:'json',type:'post',success:function(data)
	{
		bingrenVaoList = data.list;
	}}),
	
	$.get(url9,{"bck01":yiyuanId},function(data)
	{
		var list = data.list;
		zhixingkeshi1Html = "<select class='zhixingkeshi1Html'>";
//		zhixingkeshi1Html+='<option value="">--请选择--</option>';
		for(var i = 0;i<list.length;i++)
		{
			if(list[i]["bck01"] == bck01)
			{
				zhixingkeshi1Html += "<option value='"+list[i]["bck01"]+"' selected=selected>"+list[i]["bck03"]+"</option>";
			}
			else
			{
				zhixingkeshi1Html += "<option value='"+list[i]["bck01"]+"' >"+list[i]["bck03"]+"</option>";
			}
		}
		zhixingkeshi1Html += "</select>";
		
	}),
	//其它医嘱频次
	$.get(url20,{},function(data){
		var list = data.list;
		otherPinciHtml = "<select class='otherPinciHtml'>";
		for(var i = 0;i<list.length;i++)
		{
			otherPinciHtml += "<option id='"+list[i]["bdi06"]+"' value='"+list[i]["bdi01"]+"' name='"+
			list[i]["bdi08"]+"' data-bdi03='"+list[i]["bdi03"]+"'>"+list[i]["bdi02"]+"</option>";
		}
		otherPinciHtml += "</select>";
	}),
	//给药执行
	$.get(url21,{},function(data){
		var list = data.list;
		geiyaozhixingListHtml = "<select class='geiyaozhixingListHtml'>";
		var kaidankeshi = $("#kaidankeshi").val();
		for(var i = 0;i<list.length;i++)
		{
			if(list[i]["bck01"]==kaidankeshi)
			{
				geiyaozhixingListHtml += "<option value='"+list[i]["bck01"]+"' selected='selected'>"+list[i]["bck03"]+"</option>";
			}
			else
			{
				geiyaozhixingListHtml += "<option value='"+list[i]["bck01"]+"'>"+list[i]["bck03"]+"</option>";
			}
		}
		geiyaozhixingListHtml += "</select>";
	}),
	
	$.get(url13,params13,function(data)
	{
		var list = data.list;
		kaizhuyishiHtml = "<select class='kaizhuyishiHtml'>";
		for(var i =0 ;i<list.length;i++)
		{
			if(list[i].bce01==bce01)
			{
				kaizhuyishiHtml += "<option selected=true value="+list[i].bce01+" id='"+list[i].bce02+"'>"+list[i].bce03+"</option>";
			}
			else
			{
				kaizhuyishiHtml += "<option value="+list[i].bce01+" id='"+list[i].bce02+"'>"+list[i].bce03+"</option>";
			}
		}
		kaizhuyishiHtml += "</select>";
	}),
	
	$.get(url14,{},function(data){
		var list = data.list;
		qiekoudengjiHtml = "<select class='qiekoudengjiHtml'>";
		qiekoudengjiHtml +='<option value="">--请选择--</option>';
		for(var i = 0;i<list.length;i++)
		{
			qiekoudengjiHtml += "<option value="+list[i].aab02+">"+list[i]['aab02']+"</option>";
		}
		qiekoudengjiHtml += "</select>";
	})
	).done(
			function(data)
			{
				init();
				actionInPage();
			}
	);
}
function actionInPage(){
	//新开诊断编辑执行
	var isEdit = getUrlParam("isEdit");
	if(isEdit)//编辑
	 {
		var cbm01 = getUrlParam("cbm01");
		editZhenDuanEvent(cbm01);
		editAdviceMoudle.editAdviceByType(cbm01);
	 }
	else
	 {
		debugger;
		if (valueArr["p_100_105002_401"]=="1")
		{
			addZhenDuanEvent(0);//新开加载所有诊断
		}
	 }
}
// 根据项目检索
function changeBbx1(pass) 
{
	var searchStr = $("#search_medicine").val();
	var reg= /^[A-Za-z]+$/; //判断是字母
	if (reg.test(searchStr)){
		searchStr = searchStr.toLowerCase();
	}
	pass.sqltext = searchStr;
	adviceSousuo_public(pass);
//	setTimeout(function(){
//	var searchStr = $("#search_medicine").val();  
//    if(searchStr!="")
//    {  
//        $("#tree-table tr").hide().filter(":contains('"+searchStr+"')").show();  //根据tree-table的所有text()的值过滤
//    }
//    else
//    {  
//        $("#tree-table tr").show();  
//    }  
//	},200);
}

// 常用项目--门诊按照规格下达医嘱/* ScriptId(744) */
function queryAdviceInfo(obj)
{
	if(topTab !="0"){//排除电子病历
		
		if(topTab=="Xiyao" || topTab=="Zhongyao")
		{
			var url = rootUrl+"/medicine/patientcasehistory";
			var params = {};
			params.BBY01 = obj.bby01;
			params.productId = 9999;
			params.programId = 9999;
			params.paramNo = 63;
			params.bck01 = bck01;
			params.yiyuanId = yiyuanId;
			$.post(url,params,function(data)
					{
				var list = data.list;
				
				var dataObj=$.extend(list[0],{"id":obj.id},{"type":"cyxm"},{"price":obj.bby25});
				addCyxmYaopin(dataObj);
					});
		}
		else if(topTab=="Cailiao")
		{
			debugger;
			var url = rootUrl+"/treatment/getCailiaoInfoBybbx01";
			var params = {};
			params.BBX01 = obj.bbx01;
			params.bck01 = bck01;
			params.yiyuanId = yiyuanId;
			$.ajax({url:url,data:{params:JSON.stringify(params)},dataType:'json',type:"get",success:function(data)
					{
				var list = data.list;
				var dataObj=$.extend(obj,list[0],{"id":obj.id},{"type":"cyxm"},{"price":obj.price});
				addCyxmFeiyaopin(dataObj);
					}});
		}
		else
		{
			var url = rootUrl+"/treatment/gettreatmentitembyid";
			var params = {};
			params.BBX01 = obj.bbx01;
			$.post(url,params,function(data)
					{
				var list = data.list;
				var dataObj=$.extend(list[0],{"id":obj.id},{"type":"cyxm"},{"price":obj.price});
				addCyxmFeiyaopin(dataObj);
					});
		}
	}
}

// 根据常用项目增加医嘱(药品)
function addCyxmYaopin(dataObj)
{
	if(topTab=="Xiyao")
	{
		addXiyaoCyxm(dataObj);
	}
	else if(topTab=="Zhongyao")
	{
		addZhongyaoCyxm(dataObj);
	}
}
// 根据常用项目增加医嘱（非药品）
function addCyxmFeiyaopin(dataObj)
{
	if(topTab=="Jiancha")
	{
		addJianchaCyxm(dataObj);
	}else if(topTab=="Jianyan"){
		addJianyanCyxm(dataObj);
		
	}else if(topTab=="Shoushu"){
		addShoushuCyxm(dataObj);
	}
	else if(topTab=="Zhiliao"){
		
		addZhiliaoCyxm(dataObj);
	}else if(topTab == "Cailiao"){
		addcailiaoCyxm(dataObj);
	}
}

// 双击tree-table-tr的事件处理:药品
//function addBbxInfoYaopin(str)
//{
//	
//		var obj = $("#"+str).attr("data-info");
//		obj=JSON.parse(obj);
//		if(obj.item == "aitem"){
//			addYaopin(obj,str);
//		}else if(obj.item == "citem"){
//			addChangyongItem(obj);
//		}
//}


function addYaopin(obj,str)
{
	if(obj.amount == 0){
		layer.msg("该药品暂无库存，请选择其他药品",{time:2000,icon:0,skin: 'layui-layer-msg0'});
		return;
	}
	if(topTab=="Xiyao")
	{
		addXiyaoBbxInfo(obj);
	}
	else if(topTab=="Zhongyao")
	{
		debugger;
		var params = activeTabParam();
		if(obj.bef07){
			params.name = obj.bef07;
		}else if(obj.bbx05){
			params.name = obj.bbx05;
			
		}
	isRepeat =  isRepeatMedic(params);
	if(isRepeat){
		layer.msg("该药品已经存在！",
				{
				time : 3000,
				icon : 0,
				skin: 'layui-layer-msg0'
				});
				return false;
	}
		
				debugger;
				var bdm01;
				var fangji=$("#"+str).attr("a-bdm01");
				if(fangji){
				
					bdm01 = fangji
				}else{
					bdm01= obj.bda01
				}
//				var bdm01 = (fangji != undefined)?fangji:obj.bda01;
				if(bdm01&&bdm01.indexOf("8")>=0)
				{
					$.ajax({
						url:rootUrl+"/clidoctor/script817",
						type:"get",
						dataType:"json",
						data:{bbx01a:obj.bbx01},
						success:function(json)
						{
							var list = json.list;
							if(list.length<=0)
							{
								layer.msg("该方剂下暂无有效期内的药品！",{time:3000,icon:0,skin: 'layui-layer-msg0'});
							}
							for(var i = 0;i<list.length;i++)
							{
								var temp = list[i];
								temp.type = "fangji";
								$("#"+activeAdviceInputId).val("");
								addZhongyaoCyxm(temp);
							}
						}
					});
				}
				else
				{
					addZhongyaoBbxInfo(obj);
				}
			
	}
	else if(topTab=="Cailiao")
	{
		addcailiaoBbxInfo(obj);
	}
}
//// 双击tree-table-tr的事件处理：非药品
//function addBbxInfoFeiyaopin(str)
//{
//	var obj = $("#"+str).attr("data-info");
//	var obj=JSON.parse(obj);
//	if(obj.item == "aitem"){
//		feiyaopin(obj);
//	}else if(obj.item == "citem"){
//		addChangyongItem(obj);
//	}
//	
//}

function feiyaopin(obj)
{
	debugger;
	if(topTab=="Jiancha")
	{
		addJianchaBbxInfo(obj);
	}else if(topTab=="Jianyan")
	{
		addJianyanBbxInfo(obj);
	}else if(topTab=="Shoushu")
	{
		addShoushuBbxInfo(obj);
	}else if(topTab=="Zhiliao"){
		addZhiliaoBbxInfo(obj);
	}
}

// 点击医嘱页签项目事件
function typeClick(id)
{
//	debugger;
//	$("#new_order_list").find("li").on("show.bs.tab",function(){
//		var preTab = $("#new_order_list").find(".active a").attr("href");
//		if(preTab == "#Emr"){
//			
//			layer.confirm('确定病历是否已经保存，是否确认离开？', {
//				btn: ['确定', '取消'] //按钮
//			}, function(){
//				
//				$(that).tab('show');
//				layer.msg('的确很重要', {icon: 1});
//			}, function(){
//				
//				return false;
//			});
//			
//		}
//	})
//	var table = $(window.parent.document).find("#myjiezhenTableList");
//	var selectedId = $(table).jqGrid("getGridParam", "selrow");
//	var row = $(table).jqGrid("getRowData", selectedId);
//	var vac06_1 = row.vac06;
//	var vac06;
//	if(vac06_1 =="No"){
//		vac06=0;
//	}else{
//		vac06=1;
//	}
	 // 更新变量type
	 topTab=id;
	 //病历的时候改变布局
	 changeEmrAndOther();
	 if(id=='0')
	 {
		//电子病历
		 if(!($("#shuxiebingli").attr("src"))){
			 loadEmrInit();
		 }
		//		 var src = "http://192.168.1.162:8080//emrweb" + "/jsp/record/out_interface_doctor.jsp?jsessionids=" + 
//		 var src = dzbl + "/jsp/record/out_interface_doctor.jsp?jsessionids=" + 
//					$.cookie("jsessionids") + "&patientId=" + vaa01 + "&patientName=" + vaa05 + "&vaa07=" + vac01 + "&deptId=" + bck01+"&firstOrRepeat="+vac06;
//			$("#shuxiebingli").attr("src", src);
		
	 }
	 else if (id!='0')
	{
		
		if (topTab == "Zhongyao")
		{
//			$("#zhongyaocankao").parents("li").removeClass("hidden");//暂时隐藏
		}
		else
		{
			$("#zhongyaocankao").parents("li").addClass("hidden");
		}
		// 如果页面右边的种类常用项目，需要刷新；如果为治疗方案或诊断列表，不需要刷新
		if (rightTab == "changyongxiangmu")
		{
			changyongxiangmu(rightTab);
		}
		else if (rightTab == "zhenliaofangan")
		{
			zhiliaofangan(rightTab);
		}
		else if (rightTab == "chanyongzhenduan")
		{
			zhenduan(rightTab);
		}
		else if (rightTab == "zhongyaocankao")
		{
			zhongyaocankao(rightTab);
		}
	}
	 
	 setTimeout(function(){
		 var lastItem = $("#order_tab").find(".active table textarea").last();
		 lastItem.focus();
	 },200)
}

// 加载诊疗执行科室
//function queryZxksByBbx01AndBck01(bbx01,tdIndex)
//{
//	var url = rootUrl+"/clinewadvice/gettreamentoffice";
//	var params = {};
//	params.BCK01A = bck01;
//	params.BBX01 = bbx01;
//	$.post(url,params,function(data)
//			{
//		        if (data.list[0]) 
//		        {
//					zxksId = data.list[0]["bck01b"];
//					zxksMc = data.list[0]["bck03"];
//				}
//			});
//}

// 根据治疗id查询治疗医嘱方案列表
function zhenliaoAdvice(that,bbx01)
{  
//	var allXuhao = $("#west_medicine_table tbody").find("tr");
//	for(var i =0;i<allXuhao.length;i++){
//		if(allXuhao.find(""))
//	}
	debugger;
	if(that != 0){
		var thisbutton = that;
		$(thisbutton).attr("disabled",true);
		var that=this;
		
	}
	var url = rootUrl+"/clischemedefine/fetchtreatment";
	var params = {};
	params.lBBX01A = bbx01;// 治疗方案ID
	params.lACF01 = 1;
	params.lCheck = 1;
	params.lBCK01 = bck01;
	params.BCKyf = 0;
	params.bdp02 = '自费';
	params.abc02 = '普通';
	$.post(url,params,function(data){
		debugger;
		var list = data.list;
		//双击获取
//		zhiliaoChangyhongAdd(list);
		//查看详情
		laytplUrl(myurl+"/module/changyongzhiliao_layer.html",list,function(list,html){
			var index = layer.open({
				type : 1,
				scrollbar : false,
				title : "治疗方案医嘱列表",
				area : [ "60%", "90%"],
				shade : 0.3,
				maxmin : true,
				content : html,
				closeBtn:1,
				success : function() {
					
					if(that == 0){
						//处理同组问题；
//						if(list[0].bda01 == "1" ||list[0].bda01 == "2"){
							
							addTrToTbody(list);
//						}
						getCheckedAdvice();
						layer.close(index);
						//可点击时间延迟
						setTimeout(function(){
							 $("#tr_cover").remove();
						},400);
					}else{
						
						$(thisbutton).removeAttr("disabled");
						zhiliaoAdviceList = list;
						//处理同组问题；
						addTrToTbody(list);
//					getCheckedAdvice();
						$("#remove_action_zlfa").on("click",function() {
							layer.close(index);
						})
					}
				}
			})
			
		});
	});
}

//删除治疗方案

function zhenliaoDelet(that,bbx01){
	debugger;
	layer.confirm('你确定删除该方案吗', {
		btn : [ '确定', '取消' ]
	// 按钮
	}, function() {
		var url = kzzxUrl + "/bef1/deleteBef1";
		$.ajax({
	        dataType: "text",
	        type: 'get',
	        url:  url,
	        data: {
	        	bbx01  : bbx01,
	        	jsessionids:$.cookie('jsessionids')
	        },
	        success: function (data) {
//	        	zhiliaofangan("zhenliaofangan");
	        	if (data == "SUCCESS") {
					layer.msg('删除成功', {
						time : 2000,
						icon : 1,
						skin : 'layui-layer-msg1'
					});
					$(that).parents("tr").remove();
				} else {
					layer.msg('删除失败', {
						time : 2000,
						icon : 2,
						skin : 'layui-layer-msg2'
					});
				}
	        }
	    });

	}, function() {

	});
}

//编辑治疗方案
function  zhenliaoEdit(that,bbx01,treeid,treename){
	var nameText = $(that).parents("tr").find("td:eq(0)").text();
	if(treeid){
		fanganbdo01 = treeid;
	}
	if(treename){
		typename = treename;
	}else{
		
		var typename = $("#treeT").find(".node-selected").text();
	}
	//编辑放入BBX01
	var dataStr = JSON.stringify({nameText:nameText,bbx01:bbx01,typename:typename,fanganbdo01:fanganbdo01})
	$("#saveoredit_fangan").attr("data-bbx01",dataStr);
	zhiliaoChangyhongAdd(that,bbx01);
}
function addTrToTbody(dList){
    $("#zhiliaoAdvice_tbody").empty();
    for(var i= 0,len = dList.length;i<len;i++){
        var oTr = $('<tr></tr>');
        oTr.data(dList[i]);
        var vaf11_n;
        if (dList[i].bef05 == '2') {
            vaf11_n = '临嘱'
        } else if (dList[i].bef05 == '1') {
            vaf11_n = '长嘱'
        }
        var oTrHtml = String()+
            '<td class="has-input"><div class="checkbox"><label><input type="checkbox" class="magic-checkbox" /><span></span></label></div></td>'+     //选择框
            '<td class="fa-valid-time">'+(vaf11_n?vaf11_n:"")+'</td>'+                                   //期效
            '<td>'+(dList[i].nbef07?dList[i].nbef07:"")+'</td>'+                                                 //医嘱内容
            '<td class="fa-total">'+(dList[i].bef11?dList[i].bef11:"")+'</td>'+                                 //总量
            '<td class="fa-usage">'+(dList[i].fusage?dList[i].fusage:"")+'</td>'+                                                   //用法
            '<td class="fa-doctor-advice">'+(dList[i].bef15?dList[i].bef15:"")+'</td>'+                                           //医师嘱托
            '<td class="fa-execute-time">'+(dList[i].bef22?dList[i].bef22:"")+'</td>'+                          //执行时间
            '<td class="fa-execute-department">'+(dList[i].bck03?dList[i].bck03:"")+'</td>'+                    //执行科室
            '<td class="fa-first-day-num">'+(dList[i].bef24?dList[i].bef24:"")+'</td>'+                         //首日次数
            '<td class="fa-execute-property">'+(dList[i].nbef20?dList[i].nbef20:"")+'</td>'+                     //执行性质
            '<td class="fa-execute-property">'+(dList[i].lsqty?dList[i].lsqty:"")+'</td>';                         //库存情况
        oTr.html(oTrHtml);
        if(dList[i].lsqty <=0.00001){
        	$(oTr).find("td").last().css("background-color","red");
        }
        //判断将要添加的tr和它上面的tr是否是同组的，如果是同组的将它们同组显示
        //得到当前预览区域的所有tr
        var $trs = $("#zhiliaoAdvice_tbody").find('tr');
        //定义要同组td的所有class的数组
        var sameGroupTd_arr = ['fa-selectTd','fa-valid-time','fa-usage','fa-first-day-num'];
        //定义组号
        var groupId;

        var prevIndex = i-1;
        var $prevTr = $trs.eq(prevIndex);
        var prevTr_data = $prevTr.data();
        //判断是否是西药
        var isWestern = false;
        if($prevTr.length>0 && (prevTr_data.bda01=='1' || prevTr_data.bda01=='2')&&(dList[i].bda01=='1'|| dList[i].bda01=='2')){
            isWestern = true;
        }
        if($prevTr.length>0 && isWestern && prevTr_data.bbx01b == dList[i].bbx01b){

            //同组显示
            groupId = $prevTr.attr('groupId');
            //得到同组行的第一行，改变它的rowspan
            var $group_firstTr = $trs.filter('[groupId ="'+groupId+'"]').first();

            $group_firstTr.find('td').each(function(index, ele){
                var td_class = $(ele).attr('class');
                if($.inArray(td_class, sameGroupTd_arr)>-1){
                    var td_rowspan = $(ele).attr('rowspan');
                    if(td_rowspan){
                        $(ele).attr('rowspan',++td_rowspan);
                    }else{
                        $(ele).attr('rowspan', 2);
                    }
                }
            });

            oTr.find('td').each(function(index,ele){
                var td_class = $(ele).attr('class');
                if($.inArray(td_class, sameGroupTd_arr)>-1){
                    $(ele).hide();
                }
            });
        }else {
            if($trs.length == 0){
                groupId = 0;
            }else{
                groupId = i+1;
            }
        }

        oTr.attr('groupId', groupId);
        $("#zhiliaoAdvice_tbody").append(oTr);
    };
    zlsSlectCheckobx();
    //默认全部选中
    $("#zhiliaoAdvice").find('thead [type="checkbox"]').trigger('click')
};



//新开--治疗方案---常用 双击事件
function zhiliaoChangyhongAdd(that,bbx01){
	if(that.nodeName != 'LI'){
		
		tdCover($(that));
	}
	 zhenliaoAdvice(0,bbx01);
//	var url = rootUrl+"/clischemedefine/fetchtreatment";
//	var params = {};
//	params.lBBX01A = bbx01;// 治疗方案ID
//	params.lACF01 = 1;
//	params.lCheck = 1;
//	params.lBCK01 = bck01;
//	params.BCKyf = 0;
//	params.bdp02 = '自费';
//	params.abc02 = '普通';
//	$.post(url,params,function(data){
//		var dataObj = data.list;
//		//双击获取
//      for(var i=0;i<dataObj.length;i++){
////    	  dataObj[i]['bbx01'] = bbx01;
//    	  addzhiliaoAdvice(dataObj[i]);
//      }
//	});
}
// 治疗方案：选择医嘱窗口获取选中的医嘱项
function getCheckedAdvice()
{
	$("#save_action_zlfa").attr("disabled",true);
	var params = activeTabParam();
	var curXuhao
	var lastVal = $("#"+params.tbodyId).find("tr").last().find(".xiyao_yznr").val();
	if(lastVal){
		 curXuhao = $("#"+params.tbodyId).find("tr").last().index()+1;
	}else{
		
		curXuhao = $("#"+params.tbodyId).find("tr").last().index();
	}
	debugger;
	layer.msg('加载中....',
			{
			icon : 16,
			skin : 'layui-layer-msg16',
			shade : [
			0.1, '#393D49'
			],
			time : 0
			});
	var arr = $("#zhiliaoAdvice tbody td:nth-of-type(1) input:checked");
	var isSamegroup = false;
	if(arr.length > 0 ){
		
		arr.each(function(index,ele){
			var groupId = $(ele).parents("tr").attr("groupid");//后面，把groupid 当作vaf59来用；
			var dataObj=$(ele).parents("tr").data();
			dataObj = $.extend(dataObj,{'svaf59':groupId});
//		var dataObj=JSON.parse(dataStr);
			if(dataObj.bda01 == "1" || dataObj.bda01 == "2"){
				isSamegroup = true;
			}
			addzhiliaoAdvice(dataObj);
			
		});
		if(isSamegroup){
			$('#new_order_list a[href^="#Xiyao"]').last().tab('show');
			topTab="Xiyao";
			editTongzu(curXuhao);//处理同组
		}
//		$("#save_action_zlfa").removeAttr("disabled");
	}else{
		layer.msg('请选择要添加的处方',
				{
				time : 2000,
				icon : 0,
				skin: 'layui-layer-msg0'
				});
		$("#save_action_zlfa").removeAttr("disabled");
		
	}
	
}

//治疗添加数据
function addzhiliaoAdvice(dataObj){
	var bda01=dataObj.bda01;
	if(bda01=="1" || bda01 =="2")
	{
		$('#new_order_list a[href^="#Xiyao"]').last().tab('show');
		IsAddSimilarTab(dataObj);
		topTab="Xiyao";
		var data=$.extend(dataObj,{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"});
		addXiyaoCyxm(data);
	}
	//中药
	else if(bda01=="3" || bda01=="8")
	{
		 $('#new_order_list a[href^="#Zhongyao"]').last().tab('show');
		 IsAddSimilarTab(dataObj);
		 topTab="Zhongyao";
		var url = rootUrl+"/clischemedefine/getVaf1Bybbx01a_8";
		var params = {};
		params.bbx01a= dataObj.bbx01a;
		$.ajax({url:url,data:params,type:"get",dataType:"json",async:false,success:function(data){
			var list = data.list;
			dataObj = $.extend(dataObj,{type:"zhiliaofangan"});
			var jianfa;
			for(var i=0;i<list.length;i++){
				if(list[i].bda01=='T')
				{
					jianfa = list[i].bbx01c;
					dataObj.bef11_jc = list[i].bef11;
				}
			}
			formDataShow(dataObj);
			for(var i=0;i<list.length;i++){
				if(list[i].bda01=='3'){
					debugger;
					var data=$.extend(list[i],{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"},{bbx01:list[i].bbx01c},{jianfa:jianfa});
					addZhongyaoCyxm(data);
				}
			}
			
		}});
	}
	else if(bda01=="E")
	{
		 $('#new_order_list a[href^="#Jiancha"]').last().tab('show');
		 IsAddSimilarTab(dataObj);
		 topTab="Jiancha";
		var data=$.extend(dataObj,{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"});
		addJianchaCyxm(data);
	}
	else if(bda01=="L")
	{
		 $('#new_order_list a[href^="#Jianyan"]').last().tab('show');
		 IsAddSimilarTab(dataObj);
		 topTab="Jianyan";
		var data=$.extend(dataObj,{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"});
		addJianyanCyxm(data);
	}
	else if(bda01=="S")
	{
		 $('#new_order_list a[href^="#Shoushu"]').last().tab('show');
		 IsAddSimilarTab(dataObj);
		 topTab="Shoushu";
		var url = rootUrl+"/clischemedefine/getVaf1Bybbx01a_s";
		var params = {};
		var data = {};
		var fjss = [];
		params.bbx01a= dataObj.bbx01a;
		$.ajax({url:url,data:params,type:"get",dataType:"json",async:false,success:function(data){
			var list = data.list;
			if(list.length){
				for(var i=0;i<list.length;i++){
					if (list[i].bda01=="S")
					{
						fjss.push(list[i]);
					}
					else
					{
						data.mz = list[i];
					}
				}
				data.fjss = fjss;
				data=$.extend(data,dataObj,{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"});
				addShoushuCyxm(data);
			}else{
				dataObj=$.extend(dataObj,{type:"zhiliaofangan"});
				addShoushuCyxm(dataObj);
			}
		}});
	}
	else if(bda01=="4"||bda01=="M")
	{
		$('#new_order_list a[href^="#Cailiao"]').last().tab('show');
		IsAddSimilarTab(dataObj);
		topTab="Cailiao";
		var data=$.extend(dataObj,{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"});
		debugger;
		addcailiaoCyxm(data);
	}
	else
	{
		 $('#new_order_list a[href^="#Zhiliao"]').last().tab('show');
		 IsAddSimilarTab(dataObj);
		 topTab="Zhiliao";
			var data=$.extend(dataObj,{'zyyf':dataObj.bbx01c},{type:"zhiliaofangan"});
			addZhiliaoCyxm(data);
	}
	layer.closeAll();//关闭弹出层
}

var saveFangan_index;
//另存为方案
function lingcunweifanganEvent(){
	debugger;
	$("#saveoredit_fangan").attr("disabled",true);
	var bbx01_name_obj;
	var mybbx01;
	var bbx01_name =$("#saveoredit_fangan").attr("data-bbx01");
	if(bbx01_name){
		 bbx01_name_obj =JSON.parse(bbx01_name);
		 mybbx01 = bbx01_name_obj.bbx01;
	}
	var bef1 = [];
	// 西药
	var xiyao_tables = $(".left-content").find(".xiyao_table");
	$(xiyao_tables).each(function(x){
		var tableId = $(this).attr("id");
		GetBef1(tableId,bef1,x);//西药
	});
	// 中药
	var zhongyao_tables = $(".left-content").find(".zhongyao_table");
	$(zhongyao_tables).each(function(x,ele){
//		var tableId = $(this).attr("id");
		GetBef3(ele,bef1,x);//中药
	});
	// 检验
	var jianyan_tables = $(".left-content").find(".jianyan_table");
	$(jianyan_tables).each(function(x){
		var tableId = $(this).attr("id");
		GetBefL(tableId,bef1,x);//检验
	});
	// 检查
	var jiancha_tables = $(".left-content").find(".jiancha_table");
	$(jiancha_tables).each(function(x){
		var tableId = $(this).attr("id");
		GetBefE(tableId,bef1,x);//检查
	});
	// 手术
	var shoushu_tables = $(".left-content").find(".shoushu_table");
	$(shoushu_tables).each(function(x){
		var tableId = $(this).attr("id");
		GetBefS(tableId,bef1,x);//手术
	});
	// 治疗
	var zhiliao_tables = $(".left-content").find(".zhiliao_table");
	$(zhiliao_tables).each(function(x){
		var tableId = $(this).attr("id");
		GetBefT(tableId,bef1,x);//治疗
	});
	// 材料
	var cailiao_tables = $(".left-content").find(".cailiao_table");
	$(cailiao_tables).each(function(x){
		var tableId = $(this).attr("id");
		GetBef4(tableId,bef1,x);//材料
	});
	///////////////////////////////////////////////////////华丽的分割线
	if(bef1.length==0)
	{
		layer.msg('没有需要保存的方案，请检查！', {
			time : 2000,
			icon : 0,
			skin: 'layui-layer-msg0'
		});
		$("#saveoredit_fangan").removeAttr("disabled");
	}
	else
	{
		var that=this;
		var url = rootUrl+"/doctoradviceeditor/treelist1";
		var data = {"lBEH01":'9',"BCE01":bce01,"BCK01":parent.bck01s,acf01:"(1,3)"};
		$.get(url,data,function(data){
			data = $.extend(data,bbx01_name_obj);
			that.laytplUrl(myurl+"/module/lingcunweifangan.html",data,function(data,html){
				 saveFangan_index = layer.open({
					type : 1,
					//scrollbar : false,
					title : "另存为方案",
					area : [ "700px", "400px"],
					shade : 0.1,
					//maxmin : true,
					content : html,
					closeBtn:1,
					success : function() {
						$("#saveoredit_fangan").removeAttr("disabled");
						debugger;
						$('#treeFa').treeview({data: data.list});
						//增加所有的拼音码
//						$("#treeFa").find("li").each(function(i,ele){
//							$(ele).attr("data-pin",makePy($(ele).text().trim()));
//						})
					    $('#fangan_fenlei').on("click",function(){
					    	if($("#fenlei_html").is(":hidden")){
					    		var selectleft=$(this).position().left;
					    		var selecttop=$(this).position().top;
					    		$("#fenlei_html").css({left:selectleft+'px',top:selecttop+30+'px'}).slideDown(200);
					    		
					    	}else{
					    		$("#fenlei_html").slideUp(200);
					    	}
					    });
					    treeFaSelected();
					    treeFaSearch();
						$("#remove_action_cwfz").on("click",function() {
							layer.close(saveFangan_index);
						})
						$("#save_edit_fangan").on("click",function() {
							$("#save_edit_fangan").attr("disabled",true);
							saveFangan(mybbx01);
						})
					}
				})
				
			});
		});
	}
}
//tree节点选中事件
function treeFaSelected(){
	$('#treeFa').on('nodeSelected', function(event, data) {
		$("#fangan_fenlei").val(data.bdo02);
		$("#fangan_fenlei").attr("data-id",data.bdo01);
		$("#fenlei_html").slideUp(200);
	});
}
//tree节点搜索
function treeFaSearch(){
	$("#search_tree_text").on("input",function(){
		var str = $("#search_tree_text").val().toUpperCase();
		var resultList = [];
		$("#treeFa").find("li").each(function(i,ele){
			$(ele).attr("data-pin",$(ele).text().trim().toPinYin());
//			$(ele).attr("data-pin").toUpperCase().indexOf(str)>=0
			if($(ele).attr("data-pin").toUpperCase().indexOf(str)>=0){
				$(ele).show();
			}else{
				
				$(ele).hide();
			}
		})
	})
}
//新开更多页面加载

function addMoreType(){
	var data=[{"name":"检查","value":"jc"},{"name":"检验","value":"jy"},
	          {"name":"中药处方","value":"zy"},{"name":"西药处方","value":"xy"},{"name":"急诊","value":"jz"},
	          {"name":"儿童","value":"et"},{"name":"毒麻","value":"dm"},{"name":"精一","value":"jyi"},{"name":"精二","value":"jer"},
	          {"name":"手术","value":"ss"},{"name":"治疗","value":"zl"},{"name":"卫生材料","value":"wscl"}]
			
	for(var i=0;i<data.length;i++){
		var html="<li><label class='checkbox-inline'> <input type='checkbox' id='' value='' >";
		html+= data[i].name;
		html+= "</label></li>";
		$("#yizhu_more").append(html);
	}
	
}

//医师参考
function yishicankEvent(){
	var that=this;
	var data={};
	that.laytplUrl(myurl+"/module/xk_yishicankao.html",data,function(data,html){
		var index = layer.open({
			type : 1,
			//scrollbar : false,
			title : "医师参考",
			area : [ "80%", "80%"],
			shade : 0.1,
			//maxmin : true,
			content : html,
			closeBtn:1,
			success : function(index) {
			}
		})
		
	});
}


/**
 * 病人信息
 */

function reloadPatientInfo(vac01)
{
	$.ajax({
		url : rootUrl + "/patientsearch/getpatientinfo",
		data : {
			"productid" : 100,
			"programid" :103010,
			"paramno" : 29,
			"lVAC01" : vac01
		},
		type : 'post',
		dataType : 'json',
		success : function(data) {
			if(data){
				var datao = data.list[0];
				$(".three-column").data(datao);
			    laytplUrl(myurl + "/module/patient_more_info.html",datao, function(data, html) {
			    	 $(".header-content-left").empty().append(html);
			    	//加载诊断
			    		diagonoseNewOrder();
//			    	 var flag = $(".three-column").find(".header-content-left").hasClass('br_expanded');
//			    	 if(flag){
//			    		 $(".patientInfo_more").removeClass("hidden");
//			    	 }
				});
			}
		}
	});
}
//病人信息按钮控制
function seeMoreInfoEvent(){
	if(vaa01){
		var flag = $(".three-column").find(".main-header").hasClass('br_expanded');
		if(flag){
			$(".three-column").find(".main-header").removeClass('br_expanded');
			$(".three-column").find(".main-header").css('height','35px');
			$(".three-column").find('.more-info-text').text('更多');
			$(".three-column").find(".btn-transparent").find('.caret').removeClass('caret-top');
			$('.three-column-content').css('top','35px');
			/*$(".patientInfo_more").addClass("hidden");*/
			$(".header-content-left ul li").removeAttr('style');
			$(".header-content-left ul li").css('margin-right','30px');
			
		}else{
			$(".three-column").find(".main-header").addClass('br_expanded');
			$(".three-column").find(".main-header").css('height','110px');
			$(".three-column").find('.more-info-text').text('收起');
			$(".three-column").find(".btn-transparent").find('.caret').addClass('caret-top');
			$('.three-column-content').css('top','115px');
			/*$(".patientInfo_more").removeClass("hidden");*/
			$(".header-content-left ul li").css('width','auto');
			/*$(".header-content-left ul li").css('margin-right','12px');*/
		}
	}
}




